﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.SessionState;

namespace CPAIS.Web
{
    /// <summary>
    /// Summary description for Servlet
    /// </summary>
    public class Servlet : IHttpHandler, IRequiresSessionState
    {
        /// <summary>
        /// You will need to configure this handler in the Web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                //write your handler implementation here.
                context.Response.ContentType = "text/plain";

                // Gets the action information.
                string actionName = context.Request.Params[Constants.Action] as string;
                int hashCode = actionName.Trim().GetHashCode();
                var routeMap = context.Application[Constants.RouteMap] as Dictionary<int, RouteNode>;
                RouteNode node = routeMap[hashCode];

                // Creates an handler instance and processes the request.
                object handler = Activator.CreateInstance(node.HandlerType, new object[] { context });
                node.ActionInfo.Invoke(handler, null);
            }
            catch (Exception ex)
            {
                context.Response.Write(ex.Message);
            }
        }

        #endregion
    }
}